# encoding:utf-8
from database import *
import interface
from tables import message_table, error_table
import shutil
import os
import uuid


def del_key(name):
    key = Key.get(name=name)
    if key:
        key.delete()
    else:
        error_table("no such key '%s'!" % name)

def list_key():
    keys = select((k.name, k.desc) for k in Key)[:]

    if keys:
        message_table(("name", "desc"), keys)
    else:
        error_table("no key in table!")


@db_session
def add_key(**kargv):
    name = kargv['name']
    path = kargv['path']
    desc = kargv['desc']

    key = select(k.name for k in Key if k.name == name)[:]

    if not key:
        if os.path.exists(path):
            key_home = get_keyhome()
            dst_name = str(uuid.uuid1())

            dst = key_home + dst_name
            shutil.copyfile(path, dst)
            os.chmod(dst, 0600)
            # 设置文件权限

            Key(name=name, path=dst, desc=desc)

        else:
            error_table("key file not existed!")

    else:
        error_table("key name '%s' existed!" % name)


@db_session
def add_server(**kargv):
    name = kargv['name']
    host = kargv['host']
    user = kargv['username'] if kargv['username'] else "root"
    passwd = kargv['passwd']
    port = None
    group_name = kargv['group'] if kargv['group'] else "default"
    key_name = kargv['key']
    desc = kargv['desc']
    types = kargv['type']

    if types not in ("rdp","ssh"):
        error_table("the protocol must be rdp or ssh!")
        return
    elif types == "rdp":
        if key_name:
            error_table("rdp not need key,it's only needed for ssh protocol!")
            return
            
        port = kargv['port'] if kargv['port'] else "3389"
    elif types == "ssh":
        port = kargv['port'] if kargv['port'] else "22"


    if Server.get(name=name):
        error_table("host name '%s' existed!" % name)
        return

    group = None
    if group_name:
        group = Group.get(name=group_name)

        if not group:
            error_table("no such group '%s'!" % group_name)
            return

    key = None
    if key_name:
        key = Key.get(name=key_name)
        if not key:
            error_table("no such key '%s'!" % key_name)
            return

    Server(name=name, host=host, user=user, passwd=passwd, port=port, group=group, key=key, desc=desc, type=types)


@db_session
def add_group(**kargv):
    name = kargv['group']
    desc = kargv['desc'] if kargv['desc'] else "no desc"

    if name == 'default':
        error_table("can not add 'default' group!")
        return

    if Group.get(name=name):
        error_table("group '%s' existed!" % gname)
        return
    else:
        Group(name=name, desc=desc)


@db_session
def del_server(**kargv):
    name = kargv['name']
    group_name = kargv['group']
    key=kargv['key']

    if name and group_name:
        error_table("--name and --group can not be specified together!")
        return

    if name:
        server = Server.get(name=name)
        if server:
            server.delete()
        else:
            error_table("no such host name '%s'!" % name)
            return
    elif key:
        del_key(key)
    elif group_name:
        if group_name == "default":
            error_table("can not del 'default' group!")
            return

        group = Group.get(name=group_name)
        if group:
            servers = group.server
            if servers:
                for s in servers:
                    s.set(group=Group.get(name='default'))

            group.delete()

        else:
            error_table("no such group '%s'!" % group_name)
            return

    else:
        error_table("no --host or  --group specified!")


@db_session
def update_server(**kargv):
    name = kargv['name']
    host = kargv['host']
    user = kargv['username']
    passwd = kargv['passwd']
    group_name = kargv['group']
    desc = kargv['desc']
    key_name = kargv['key']
    port = kargv['port'] if kargv['port'] else None

    server = Server.get(name=name)
    if not server:
        error_table("no such host name '%s'!" % name)
        return

    group = None
    if group_name:
        group = Group.get(name=group_name)

        if not group:
            error_table("no such group '%s'!" % group_name)
            return

    if server.group == group:
        error_table("'%s' group name is aleady '%s'!" % (name, group_name))
        return

    key = None
    if key_name:
        key = Key.get(name=key_name)
        if not key:
            error_table("no such key '%s'!" % key)
            return

    old_args = [server.host, server.user, server.passwd, server.port, server.group, server.key, server.desc]
    input_args = [host, user, passwd, port, group, key, desc]
    new_args = [v if v else old_args[k] for (k, v) in enumerate(input_args)]

    server.set(host=new_args[0], user=new_args[1], passwd=new_args[2], port=new_args[3], group=new_args[4], key=new_args[5], desc=new_args[6])


@db_session
def update_group(**kargv):
    group_name = kargv['group']
    newgroup_name = kargv['new_group']
    desc = kargv['desc']

    if group_name == "default":
        error_table("default group can't be changed!")
        return

    if not newgroup_name and not desc:
        error_table("no -g or  -m specified!")
        return

    if newgroup_name == group_name:
        error_table("group name '%s' existed!" % group_name)
        return

    if newgroup_name == "default":
        error_table("new group name can't be 'default'!")
        return

    if Group.get(name=newgroup_name):
        error_table("group name '%s' existed!" % newgroup_name)
        return

    group = Group.get(name=group_name)
    if group:
        old_args = (group.name, group.desc)
        input_args = (newgroup_name, desc)
        new_args = [v if v else old_args[k]
                    for (k, v) in enumerate(input_args)]

        group.set(name=new_args[0], desc=new_args[1])
    else:
        error_table("no such group '%s'!" % group_name)


def get_server(name):
    """
    返回登陆用数据
    """
    server = Server.get(name=name)

    return server if server else None


@db_session
def ssh_login(**kargv):
    name = kargv['name']
    show = kargv['show']

    server = get_server(name)

    if not server:
        error_table("no such name '%s'!" % name)
        return

    types=server.type

    print "please waitting ..."
    if types == "ssh":
        key_file = None

        if server.key:
            key_file = server.key.path

        if server.passwd:
            interface.clipboard(server.passwd)

        interface.ssh(server.host, server.user, server.passwd, server.port, key_file, show)
    elif types == "rdp":
        interface.rdp(server.host, server.user, server.passwd, server.port, show)


@db_session
def info(**kargv):
    name = kargv['name']

    server = [list(s) for s in select((s.name, s.host, s.group.name, s.desc, s.user, s.port, s.passwd, s.type)
                    for s in Server if s.name == name)[:]]

    for s in server:
        if not s[3]:s[3]=""

    message_table(
        ("name", "host", "group", "description", "user", "port", "password", "type"), server)


@db_session
def lists(**kargv):
    name = kargv['group']
    all = kargv['all']
    key = kargv['key']

    if name and all and key:
        return

    #按group name 排序
    if all:
        servers = [list(s) for s in select((s.name,s.group.name,
            s.desc,s.user,s.port,s.key,s.type) for s in Server)[:]]

        servers.sort(key=lambda s:s[1])

        for s in servers:
            if s[-2]:s[-2]=s[-2].name
            else:s[-2]=""

            if not s[2]:s[2]=""

        message_table(("name", "group", "description", "user", "port", "key", "type"), servers)
    elif name:
        servers = select((g.server.name, g.name, g.server.desc, g.server.user, g.server.port)
                         for g in Group if g.name == name)[:]
        message_table(("name", "group", "description", "user", "port"), servers)
    elif key:
        list_key()
    else:
        groups = select((g.name, g.desc) for g in Group)[:]
        message_table(("group", "description"), groups)
